package com.sxdx.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@SuppressWarnings("all")
public class CharacterEncodingFilter implements Filter{
	private Logger logger = LogManager.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());
	private String characterEncoding;
	private String ip;
	private boolean enabled;
	public void init(FilterConfig config) throws ServletException {
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		characterEncoding = config.getInitParameter("characterEncoding");
		enabled = "true".equalsIgnoreCase(characterEncoding.trim())||"1".equalsIgnoreCase(characterEncoding.trim());
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		logger.trace("客户端："+getClientLocation((HttpServletRequest) request));
		if (enabled || characterEncoding != null) {
			request.setCharacterEncoding(characterEncoding);
			response.setCharacterEncoding(characterEncoding);
		}
//		String a = ((HttpServletRequest) request).getRequestURI();
//		String b = a.substring(a.lastIndexOf("/")+1, a.lastIndexOf("."));
//		System.out.println(b);
		chain.doFilter(request, response);
	}
	public void destroy() {
		characterEncoding = null;
	}
	
	private String getClientLocation(HttpServletRequest request){
		ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String local = request.getScheme() + "://" + ip + ":" + request.getServerPort()+request.getRequestURI();
		return local;
	}
	
}
